#' ---
#' title: "Whose Dimension is it anyway: CCES Legislator and Citzins Scaling"
#' author: "Lukas F. Stoetzer"
#' ---

#' Script estimates irt models for Senator Representation Study

  # Libraries
  library(pscl)

  # Set values for mcmc
  sample <- 120000
  burnin <- 20000
  thinin <- 100

  # Start Time
  start.time <- Sys.time()
  
# 1) Prepare Data  =========

  # Load SRS Study (Downloaded from Dataverse https://doi.org/10.7910/DVN/IIYGGX)
  load("Formatted+info+votes+matrices.RData")
  load("Survey+Responses+Dataframe.Rdata")
  
  # Starting Values to assure converagence
  init_sen  <- ifelse(sen.all.raw$party.x==200, 1, -1) # set republican start value at 1; democrat -1
  init_sen[is.na(init_sen)] <- 0
  init_resp <- ifelse(survey.wd$pid == 7, 1, 
                      ifelse(survey.wd$pid== 1, -1, 0)) # set strong republican start value at 1; strong democrat -1; others 0
  init_resp[is.na(init_resp)] <- 0
  
# 2) Legislators & Respondent scaling ======

  # Legsilator Based Scaling
   leg_srs <- ideal(rollcall(VOTES.SEN.SMALL), 
                    maxiter=sample, thin=thinin, burnin=burnin,
                    normalize=T,
                    startvals=list(x= init_sen),
                    store.item=TRUE)
  
  # Legsilator Based Scaling
   resp_srs <- ideal(rollcall(VOTES.RESP.SMALL), 
                     maxiter=sample, thin=thinin, burnin=burnin,
                     normalize=T,
                     startvals=list(x= init_resp),
                     store.item=TRUE)

# 4) Post-Estimation ========= 

  # Save
    save(leg_srs,resp_srs,file="res_srs_scaling.Rdata")
  
    rm(leg_srs,resp_srs)

    # Time Track
    end.time <- Sys.time()
    time.taken <- end.time - start.time
    print(time.taken)
    